import styles from './clock.module.css'; // 导入 LESS 文件
import {
  Zero,
  One,
  Two,
  Three,
  Four,
  Five,
  Six,
  Seven,
  Eight,
  Nine,
  Dash,
  Colon,
} from '../../assets/index';
import { useState, useEffect } from 'react'; // 导入 React 中的 useState 钩子
import getSentences from '../api/sentences';

const getSvgComponent = (digit) => {
  switch (digit) {
    case '0':
      return <Zero />;
    case '1':
      return <One />;
    case '2':
      return <Two />;
    case '3':
      return <Three />;
    case '4':
      return <Four />;
    case '5':
      return <Five />;
    case '6':
      return <Six />;
    case '7':
      return <Seven />;
    case '8':
      return <Eight />;
    case '9':
      return <Nine />;
    default:
      return <div>{digit}</div>;
  }
};

const Item = ({ displayTime }) => {
  return (
    <div className={styles.item}>{displayTime.split('').map((item) => getSvgComponent(item))}</div>
  );
};
export default function Clock() {
  const [displayTime, setDisplayTime] = useState(['0', '0', '0']); // 时分秒
  const [displayDate, setDisplayDate] = useState(['0', '0', '0']); // 年月日
  const [sentences, setSentences] = useState({ name: '-', from: '-' });

  const [loading, setLoading] = useState(false);

  useEffect(() => {
    getSentences().then((res) => {
      setSentences({ ...res.result });
    });
  }, []);

  useEffect(() => {
    const updateTime = () => {
      const timer = new Date();
      setDisplayDate(
        [timer.getFullYear(), timer.getMonth() + 1, timer.getDate()].map((item, index) =>
          index === 0 ? `${item}` : item.toString().padStart(2, '0')
        )
      );
      setDisplayTime(
        [timer.getHours(), timer.getMinutes(), timer.getSeconds()].map((item) =>
          item.toString().padStart(2, '0')
        )
      );
      setLoading(true);
    };

    updateTime(); // 立即执行一次
    const interval = setInterval(updateTime, 1000); // 每秒更新

    return () => clearInterval(interval); // 清理定时器
  }, []); // 空依赖数组

  return (
    <div className={styles.container}>
      {loading && (
        <>
          <div className={styles.date}>
            <Item displayTime={displayDate[0]} />
            <Dash />
            <Item displayTime={displayDate[1]} />
            <Dash />
            <Item displayTime={displayDate[2]} />
          </div>
          <div className={styles.time}>
            <Item displayTime={displayTime[0]} />
            <Colon /> <Item displayTime={displayTime[1]} />
            <Colon />
            <Item displayTime={displayTime[2]} />{' '}
          </div>
          <div className={styles.clockFooter}>
            {sentences.name} —— {sentences.from}
          </div>
        </>
      )}
    </div>
  );
}
